//
//  Rrcorder.m
//  Recorder
//
//  Created by hetao on 14-7-29.
//  Copyright (c) 2014年 hetao. All rights reserved.
//

#import "Rrcorder.h"

@implementation Rrcorder

+ (id)defule
{
    static Rrcorder *rrcoreder;
    if(!rrcoreder)
    {
        rrcoreder=[[Rrcorder alloc]init];
    }
    return rrcoreder;
}
///开始录音
- (void)recorderStater
{
    _isplay=YES;
    //初始化录音服务（询问是否允许使用麦克）
    audsession=[AVAudioSession sharedInstance];
    
    //设置使用服务的权限（当前为录制和播放:播放为听筒播放）
    [audsession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
    
    //设置是否可以使用该服务
    [audsession setActive:YES error:nil];
    
    //设置录音的一些数据（比如采样率）
     NSDictionary *setting = [[NSDictionary alloc] initWithObjectsAndKeys: [NSNumber numberWithFloat: 44100.0],AVSampleRateKey,
                              [NSNumber numberWithInt: kAudioFormatLinearPCM],AVFormatIDKey,
                              [NSNumber numberWithInt:16],AVLinearPCMBitDepthKey,
                              [NSNumber numberWithInt: 2], AVNumberOfChannelsKey,
                              [NSNumber numberWithBool:NO],AVLinearPCMIsBigEndianKey,
                              [NSNumber numberWithBool:NO],AVLinearPCMIsFloatKey,nil];
    
    //设置音频文件保存地址
     tmpFile = [NSURL fileURLWithPath:
               [NSTemporaryDirectory() stringByAppendingPathComponent:
                [NSString stringWithFormat: @"%@.%@",@"cj",@"caf"]]];
    
    recorder=[[AVAudioRecorder alloc]initWithURL:tmpFile settings:setting error:nil];
    [recorder setDelegate:self];
    
    recorder.meteringEnabled=YES;//设置在录音时可以访问数据变化
   
   // [recorder recordAtTime:[recorder deviceCurrentTime]+1];//一秒后开始把录音写入文件
    [recorder prepareToRecord];//准备录音
    [recorder record];//开始录音
    
    //开始录音采样
    if(timer)
    {
        [timer invalidate];
        timer=nil;
    }
    
  
    timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(detectionVoice) userInfo:nil repeats:YES];
    
}

///输出声音录入音量大小
- (void)detectionVoice
{
   
    if(view)
    {
        view.hidden=NO;
        [tsimage startAnimating];
    }else
    {
        [self allocview];
    }
}
///停止录音
- (NSDictionary *)recorderStop
{
    if(_isplay)
    {
        _isplay=NO;
    }else
    {
        return nil;
    }
    [recorder stop];
    [timer invalidate];//停止录音采样
    
    
    //获取录音数据
    NSData *data=[NSData dataWithContentsOfURL:tmpFile];
    //获取录音的时长  以秒为单位
    NSString *str=[self recorederTime:data];
    NSLog(@"**%@",str);
    NSNumber *number=[NSNumber numberWithInt:[str intValue]];
    
    NSDictionary *dic=[[NSDictionary alloc]initWithObjectsAndKeys:number,@"time", data,@"data",nil];
    
    view.hidden=YES;
    [tsimage stopAnimating];
    return dic;
}

///播放录音
- (void)recorderplayerData:(id)data
{
    //设置音频服务使用扬声器播放声音
    [audsession setCategory:AVAudioSessionCategoryPlayback error:nil];
    NSError *error;
    if(data)
    {
        if([data isKindOfClass:[NSString class]])//保存录音文件
        {
            NSArray *namearr=[data componentsSeparatedByString:@"/"];
            NSString *name;
            NSData *audioData;
            NSString *path=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
            if(namearr.count<=2)//这是判断如果只有文件名的情况，得到的数据只有两组，
            {
              name=namearr[0];
            }else
            {
              name=namearr[namearr.count-1];
            }
            
             path=[path stringByAppendingFormat:@"/audio/%@",name];
            audioData=[NSData dataWithContentsOfFile:path];
            if(audioData.length>100)
            {
               audplayer=[[AVAudioPlayer alloc]initWithData:audioData error:&error];
            }else
            {
                
                audioData=[NSData dataWithContentsOfURL:[NSURL URLWithString:data]];
                [self saveAudioName:name data:audioData];
                audplayer=[[AVAudioPlayer alloc]initWithData:audioData error:&error];
            }

            
        }else
        {
            audplayer=[[AVAudioPlayer alloc]initWithData:data error:&error];
        }
    }else
    {
        audplayer=[[AVAudioPlayer alloc]initWithContentsOfURL:tmpFile error:&error];
    }
    NSLog(@"%.2f",[audplayer duration]);
    audplayer.volume=1;//设置播放音量大小 0~1
    if (error) {
        NSLog(@"error:%@",[error description]);
        return;
    }
    //准备播放
    [audplayer prepareToPlay];
    [audplayer setDelegate:self];
    //播放
    [audplayer play];
}

///停止播放
- (void)stoprecorder
{
    if(audplayer)
    {
        [audplayer stop];
        [self  stopplayNotification];
    }
}
///获取音频文件声音时长
- (NSString *)recorederTime:(NSData *)data
{
    NSError *error;
    AVAudioPlayer *aplayer=[[AVAudioPlayer alloc]initWithData:data error:&error];
    return [NSString stringWithFormat:@"%.0f",[aplayer duration]];
}

///保存录音文件
- (NSString *)saveAudioName:(NSString *)name  data:(NSData *)data
{
    NSString *path=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    path=[path stringByAppendingString:@"/audio"];
    NSFileManager *file=[NSFileManager defaultManager];
    if(![file fileExistsAtPath:path])
    {
        [file createDirectoryAtPath:path withIntermediateDirectories:YES attributes:NO error:nil];
    }
    
    path=[path stringByAppendingFormat:@"/%@",name];
    [file createFileAtPath:path contents:data attributes:nil];
    return path;
}

///下载录音文件并保存
- (NSData *)doloadAudioUrl:(NSString *)url FileName:(NSString *)name
{
    NSData *audioData;
    
    NSString *path=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    path=[path stringByAppendingFormat:@"/audio/%@",name];
    audioData=[NSData dataWithContentsOfFile:path];
    if(audioData)
    {
        return audioData;
    }
    
    return nil;
}
///创建录音提示视图
- (void)allocview
{
    CGRect rx = [ UIScreen mainScreen ].bounds;
    view=[[UIView alloc]initWithFrame:CGRectMake(rx.size.width/2-40, rx.size.height/2-18, 80, 80)];
    [view setBackgroundColor:[UIColor whiteColor]];
    [view.layer setCornerRadius:6.0];
    UIImageView *imageview=[[UIImageView alloc]initWithFrame:CGRectMake(25, 5, 16, 38)];
    UILabel *lable=[[UILabel alloc] initWithFrame:CGRectMake(0, 60, 80, 20)];
    [lable setFont:[UIFont systemFontOfSize:12]];
    lable.text=@"上滑可操作";
    [lable setTextColor:[UIColor blackColor]];
    lable.textAlignment=NSTextAlignmentCenter;
    [imageview setImage:[UIImage imageNamed:@"sheng1@2x"]];
    
    [view addSubview:imageview];
    
    tsimage =[[UIImageView alloc]initWithFrame:CGRectMake(43, 5, 18, 38)];
    tsimage.animationImages=[[NSArray alloc]initWithObjects: [UIImage imageNamed:@"shengy1x"], [UIImage imageNamed:@"shengy2x"], [UIImage imageNamed:@"shengy3x"], nil];
    [tsimage setAnimationDuration:2];
    [tsimage setAnimationRepeatCount:0];
    [tsimage startAnimating];
    [view addSubview: tsimage];
    [view addSubview: lable];
    [[[UIApplication sharedApplication] windows][0] addSubview:view];
}
#pragma mark -------AVAudioSiossn代理---------
- (void)inputIsAvailableChanged:(BOOL)isInputAvailable
{
    if(isInputAvailable)
    {
        NSLog(@"可使用录音");
    }else
    {
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"当前麦克风访问受限" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }
}

#pragma marek---------AVAudioRecorder代理------
- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag
{
    if(flag)
    {
        NSLog(@"录制成功");
    }else
    {
        NSLog(@"录制失败");
    }
   
}

// 音频播放完成时

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
    
    // 音频播放完成时，调用该方法。
    
    // 参数flag：如果音频播放无法解码时，该参数为NO。
    
    //当音频被终端时，该方法不被调用。而会调用audioPlayerBeginInterruption方法
    
    // 和audioPlayerEndInterruption方法
     [self  stopplayNotification];
    
    
    
    
}


// 解码错误

- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error{
    
    NSLog(@"解码错误！");
    [self  stopplayNotification];
    
    
}


// 当音频播放过程中被中断时

- (void)audioPlayerBeginInterruption:(AVAudioPlayer *)player{
    
    // 当音频播放过程中被中断时，执行该方法。比如：播放音频时，电话来了！
    
    // 这时候，音频播放将会被暂停。
    [self  stopplayNotification];
    
}

///停止播放时发出通知消息
- (void)stopplayNotification
{
    [[NSNotificationCenter defaultCenter] postNotificationName:STOPPLAY object:self userInfo:nil];
}
@end
